import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getTimeStamp } from '@/utils/auth'
import router from '@/router'
const TimeOut = 864000 // 定义超时时间
// create an axios instance

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_HOME_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // 判断是否有token存在
    if (store.getters.token) {
      if (IsCheckTimeOut()) {
        // 清除token和管理员信息1
        store.dispatch('user/logout') // 调用登出操作
        // 转跳登入页
        router.push('/login')
        return Promise.reject(new Error('登入超时！')) // 提示登入超时
      }
      // 请求头添加token
      config.headers['token'] = store.getters.token
      // 请求头添加userId
      config.headers['userId'] = store.getters.userId
    }

    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    console.log(response)
    const data = response.data
    return data
  },
  (err) => {
    console.log(err)
    if (err.response.status === 401) {
      // 退出登录，跳转到登录页面
      // 清空用户信息
      // 清空token
      store.dispatch('user/logout')
      // 跳转到登录
      router.push('/login')
      // 错误提示
      Message.info('登录状态已过期,请重新登录')
      return Promise.reject(err)
    }
  }
)

// 是否超时函数
function IsCheckTimeOut() {
  var currentTime = Date.now()
  var timeStamp = getTimeStamp()
  return (currentTime - timeStamp) / 1000 > TimeOut
}

export default service
